package start.doubudouyin.utils;

import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.EncoderException;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class VideoRead {
    // 默认存储目录
    private static final String DEFAULT_STORAGE_DIR = "D:\\Practice Project\\video";
    // 视频大小限制(30MB)
    private static final double MAX_VIDEO_SIZE_MB = 30.0;
    // 视频时长限制(60秒)
    private static final double MAX_VIDEO_DURATION_SECONDS = 60.0;

    // 配置参数
    private static String contextPath = "/";
    @Setter
    private static int port = 8080;
    private static String videoUrlPath = "/video"; // 视频访问路径前缀

    // 私有构造函数，防止实例化
    private VideoRead() {}

    // 设置配置参数的静态方法
    public static void setContextPath(String path) {
        if (path != null) {
            contextPath = path;
        }
    }

    public static void setVideoUrlPath(String path) {
        if (path != null) {
            videoUrlPath = path;
        }
    }

    public static VideoProcessResult processVideoFile(MultipartFile file) throws IOException {
        return processVideoFile(file, DEFAULT_STORAGE_DIR);
    }

    public static VideoProcessResult processVideoFile(MultipartFile file, String targetDir)
            throws IOException {
        // 验证文件是否为空
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传的视频文件为空");
        }

        // 创建目标目录（如果不存在）
        Path targetPath = Paths.get(targetDir);
        if (!Files.exists(targetPath)) {
            Files.createDirectories(targetPath);
        }

        // 生成唯一文件名
        String fileName = file.getOriginalFilename();
        String uniqueFileName = generateUniqueFileName(fileName);
        File targetFile = new File(targetDir, uniqueFileName);

        // 保存文件
        try {
            file.transferTo(targetFile);

            // 检查视频大小
            double videoSize = getVideoSize(targetFile.getAbsolutePath());
            if (videoSize > MAX_VIDEO_SIZE_MB) {
                boolean deleted = targetFile.delete();
                if (!deleted) {
                    throw new IOException("删除临时文件失败: " + targetFile.getAbsolutePath());
                }
                throw new IllegalArgumentException("视频大小超过30MB限制");
            }

            // 检查视频时长
            double videoDuration = getVideoTime(targetFile.getAbsolutePath());
            if (videoDuration > MAX_VIDEO_DURATION_SECONDS) {
                boolean deleted = targetFile.delete();
                if (!deleted) {
                    throw new IOException("删除临时文件失败: " + targetFile.getAbsolutePath());
                }
                throw new IllegalArgumentException("视频时长超过1分钟限制");
            }

            // 返回处理结果
            return new VideoProcessResult(
                    uniqueFileName,
                    file.getOriginalFilename(),
                    file.getSize(),
                    file.getContentType(),
                    videoSize,        // 大小（MB）
                    videoDuration     // 时长（秒）
            );
        } catch (Exception e) {
            // 处理失败时删除已创建的文件
            if (targetFile.exists()) {
                boolean deleted = targetFile.delete();
                if (!deleted) {
                    throw new IOException("删除临时文件失败: " + targetFile.getAbsolutePath());
                }
            }
            throw new IOException("视频处理失败: " + e.getMessage(), e);
        }
    }

    // 生成前端可访问的视频URL
    public static String generateVideoUrl(String storedFileName) {
        // 处理contextPath，移除多余斜杠
        String contextPathTrimmed = contextPath.trim();
        contextPathTrimmed = contextPathTrimmed.replaceAll("//", "/");
        if (contextPathTrimmed.startsWith("/")) {
            contextPathTrimmed = contextPathTrimmed.substring(1);
        }
        if (contextPathTrimmed.endsWith("/")) {
            contextPathTrimmed = contextPathTrimmed.substring(0, contextPathTrimmed.length() - 1);
        }

        // 处理videoUrlPath，确保以斜杠开头
        String videoPath = videoUrlPath.trim();
        if (!videoPath.startsWith("/")) {
            videoPath = "/" + videoPath;
        }

        // 拼接标准URL
        StringBuilder urlBuilder = new StringBuilder("http://localhost:");
        urlBuilder.append(port);

        if (!contextPathTrimmed.isEmpty()) {
            urlBuilder.append("/").append(contextPathTrimmed);
        }

        urlBuilder.append(videoPath).append("/").append(storedFileName);
        return urlBuilder.toString();
    }

    private static String generateUniqueFileName(String originalFileName) {
        String extension = getFileExtension(originalFileName);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        return uuid + (extension.isEmpty() ? "" : "." + extension);
    }

    private static String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public record VideoProcessResult(
            String storedFileName,
            String originalFileName,
            long fileSize,
            String contentType,
            double videoSizeMB,        // 视频大小（MB）
            double videoTimeSeconds    // 视频时长（秒）
    ) {}

    public static double getVideoSize(String filePath) {
        return IconRead.getIconSize(filePath);
    }

    public static double getVideoTime(String filePath) {
        ws.schild.jave.MultimediaObject mediaObject =
                new ws.schild.jave.MultimediaObject(new File(filePath));
        try {
            return mediaObject.getInfo().getDuration() / 1000.0;
        } catch (EncoderException e) {
            return -1;            //不抛出异常，时长解析失败就让时长为-1秒，然后在控制层进行判断
        }
    }
}